<?php

declare(strict_types=1);

namespace app\backend\controller\crm;

use app\common\controller\Basic;
use app\common\service\crm\ContractService;
use app\common\service\crm\ContractProductService;
use app\common\service\hrm\FilesService;
use app\common\service\sys\UserService;

/**
 * 合同表 控制器
 * @author 吕玉冰
 * @date  2022-07-23
 * @copyright ©2022 泉州市盛筑信息科技有限公司 版权所有
 */
class Contract extends Basic
{

    // 初始化
    protected function initialize()
    {
        parent::initialize();
        // 当前控制器服务实例化
        $this->service = new ContractService();
        $this->pService = new ContractProductService();
    }

    /**
     * 列表
     */
    public function index()
    {
        if ($this->request->isGet()) {
            $data = input('param.');
            return json($this->service->_list($data));
        }
        return _jerr(1000);
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $data = input('param.');
            $this->_form_filter($data);
            return json($this->service->saveForm($data));
        }
        if ($this->request->isGet()) {
            $where = [];
            $where[] = ['num', 'like', 'C' . date("Ymd") . "%"];
            $c = $this->service->getTotal($where) + 1;
            return _jok('ok', [
                'num' => 'C' . date("Ymd") . sprintf('%05s', $c),
                'einfo' => (new UserService())->getEmployeeInfo($this->user['id']),
                'fi' => [],
            ]);
            return _jok('ok', $data);
        }
        return _jerr(1000);
    }

    /**
     * 编辑
     */
    public function edit()
    {
        $id = input('id/d', 0);
        if ($id === 0) {
            return _jerr(1022);
        }
        if ($this->request->isPost()) {
            $data = input('param.');
            $this->_form_filter($data);
            return json($this->service->saveForm($data));
        }
        if ($this->request->isGet()) {
            $data = $this->service->getInfoById($id);
            if ($data['state'] == 2) {
                return _jerr('当前合同已被锁定,无法修改!');
            }
            $where = [];
            $where[] = ["contract_id", '=', $id];
            $pdata = $this->pService->getListAll($where, ['id' => 'asc'], ["product_id", "price", "num"]);
            $product_list = [];
            foreach ($pdata as $k => $v) {
                $temp = [];
                $temp['product_id'] = $v['product_id'];
                $temp['price'] = $v['price'];
                $temp['num'] = $v['num'];
                $product_list[] = $temp;
            }
            $data['product_list'] = $product_list;
            $data['fi'] = FilesService::getFilesJson([
                'id' => $id,
                'table_name' => 'crm_contract'
            ]);
            return _jok('ok', $data);
        }
        return _jerr(1000);
    }

    /**
     * 添加编辑-表单数据处理
     */
    protected function _form_filter(&$data)
    {
        $data = rq_decode($data); // 前端已 encodeURIComponent 编码（最深二维数组） 后端需要解码
        $data["create_user_id"] = $this->user['id'];
        $data["create_user_name"] = $this->user['real_name'];
        $data["owner_user_id"] = $this->user['id'];
        $data["owner_user_name"] = $this->user['real_name'];
    }

    /**
     * 删除
     */
    public function del()
    {
        if ($this->request->isPost()) {
            $id = input('id', '');
            $data = $this->service->getInfoById($id);
            if ($data['state'] == 2) {
                return _jerr('当前合同已被锁定,无法删除!');
            }
            if ($id === 0) {
                return _jerr(1002);
            }
            return json($this->service->_del($id));
        }
        return _jerr(1000);
    }

    public function rebuildNum()
    {
        if ($this->request->isPost()) {
            $old_num = input('old_num', '');
            $where = [];
            $where[] = ['num', '=', $old_num];
            if ($this->service->getTotal($where) == 0) {
                return _jerr("检查到合同编码不存在,无需重新生成!");
            }
            $where = [];
            $where[] = ['num', 'like', 'C' . date("Ymd") . "%"];
            $c = $this->service->getTotal($where) + 1;
            return _ok("获取成功!", 'C' . date("Ymd") . sprintf('%05s', $c));
        }
        return _jerr(1000);
    }
}
    